package com.hub.controller;

import com.hub.utils.ApiResultObject;
import com.hub.service.IFileService;
import com.hub.utils.UploadFileResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author hub
 * @version 1.0
 * @date 2020/5/15 14:36
 * @description:
 */

@Slf4j
@Api(value="文件上传下载接口")
@RestController
@RequestMapping(value="file")
public class FileController {

    @Autowired
    private IFileService fileService;

    //@RestAuth(isPublic = true)
    @ApiOperation("上传单个文件")
    @PostMapping("/upload")
    public ApiResultObject uploadFile(@RequestParam("file") MultipartFile file){

        return ApiResultObject.success(saveUploadFile(file));
    }

    //@RestAuth(isPublic = true)
    @ApiOperation("上传多个文件")
    @PostMapping("/upload/multiple")
    public ApiResultObject uploadMultipleFiles(@RequestParam("files") MultipartFile[] files) {
        List<UploadFileResponse> list = Arrays.stream(files)
                .map(this::saveUploadFile)
                .collect(Collectors.toList());

        return ApiResultObject.success(list);
    }

    //@RestAuth(isPublic = true)
    @ApiOperation("下载文件")
    @GetMapping("/download/{fileName:.+}")
    public ResponseEntity<Resource> downloadFile(@PathVariable String fileName, HttpServletRequest request) {
        // Load file as Resource
        Resource resource = fileService.loadFileAsResource(fileName);

        // Try to determine file's content type
        String contentType = null;
        try {
            contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
        } catch (IOException ex) {
            log.info("Could not determine file type.");
        }

        // Fallback to the default content type if type could not be determined
        if(contentType == null) {
            contentType = "application/octet-stream";
        }

        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(contentType))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                .body(resource);
    }

    private UploadFileResponse saveUploadFile(MultipartFile file) {
        String fileName = fileService.storeFile(file);

        String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath()
                .path("/downloadFile/")
                .path(fileName)
                .toUriString();
        return new UploadFileResponse(fileName, fileDownloadUri,
                file.getContentType(), file.getSize());
    }
}
